package net.lab1024.sa.admin.module.business.quotation.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import jakarta.validation.Valid;
import net.lab1024.sa.admin.module.business.quotation.dao.QuotationDao;
import net.lab1024.sa.admin.module.business.quotation.dao.QuotationItemsDao;
import net.lab1024.sa.admin.module.business.quotation.domain.entity.QuotationEntity;
import net.lab1024.sa.admin.module.business.quotation.domain.entity.QuotationItemsEntity;
import net.lab1024.sa.admin.module.business.quotation.domain.form.QuotationAddForm;
import net.lab1024.sa.admin.module.business.quotation.domain.form.QuotationItemsQueryForm;
import net.lab1024.sa.admin.module.business.quotation.domain.form.QuotationQueryForm;
import net.lab1024.sa.admin.module.business.quotation.domain.form.QuotationUpdateForm;
import net.lab1024.sa.admin.module.business.quotation.domain.vo.QuotationDetailVo;
import net.lab1024.sa.admin.module.business.quotation.domain.vo.QuotationItemsVO;
import net.lab1024.sa.admin.module.business.quotation.domain.vo.QuotationVO;
import net.lab1024.sa.admin.module.business.template.constant.QuotationTypeEnum;
import net.lab1024.sa.admin.module.business.template.domain.entity.QuotationTemplateItemsEntity;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import net.lab1024.sa.base.module.support.datatracer.constant.DataTracerTypeEnum;
import net.lab1024.sa.base.module.support.datatracer.service.DataTracerService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 报价信息 Service
 *
 * @Author zzx
 * @Date 2025-08-07 19:37:04
 * @Copyright zzx
 */

@Service
public class QuotationService {

    @Resource
    private QuotationDao quotationDao;
    @Resource
    private QuotationItemsDao quotationItemsDao;
    @Resource
    private DataTracerService dataTracerService;

    /**
     * 分页查询
     */
    public PageResult<QuotationVO> queryPage(QuotationQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<QuotationVO> list = quotationDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(QuotationAddForm addForm) {
        QuotationEntity quotationEntity = SmartBeanUtil.copy(addForm, QuotationEntity.class);
        quotationDao.insert(quotationEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     */
    public ResponseDTO<String> update(QuotationUpdateForm updateForm) {
        QuotationEntity quotationEntity = SmartBeanUtil.copy(updateForm, QuotationEntity.class);
        quotationDao.updateById(quotationEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        quotationDao.batchUpdateDeleted(idList, true);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long quotationId) {
        if (null == quotationId){
            return ResponseDTO.ok();
        }
        quotationDao.updateDeleted(quotationId, true);
        return ResponseDTO.ok();
    }

    /**
     * 获取报价单详情
     * @param quotationId 报价单id
     * @return
     */
    public QuotationDetailVo queryDetail(Long quotationId) {
        QuotationDetailVo detail = new QuotationDetailVo();
        if (quotationId == -1) {
            detail = getNullDetail();
        } else {
            QuotationEntity quotationEntity = quotationDao.selectById(quotationId);
            if (quotationEntity != null) {
                detail = SmartBeanUtil.copy(quotationEntity, QuotationDetailVo.class);
                detail.setList(quotationDao.queryItemsById(quotationId));
            }
        }
        return detail;
    }

    /**
     * 返回空数据
     * @return
     */
    public QuotationDetailVo getNullDetail() {
        QuotationDetailVo detail = new QuotationDetailVo();
        List<QuotationItemsVO> items = new ArrayList<>();
        items.add(new QuotationItemsVO("主材1", "规格1", QuotationTypeEnum.MAIN_MATERIALS.getValue()));
        items.add(new QuotationItemsVO("主材2", "规格2", QuotationTypeEnum.MAIN_MATERIALS.getValue()));
        items.add(new QuotationItemsVO("损耗", "", QuotationTypeEnum.LOSS.getValue()));
        items.add(new QuotationItemsVO("配件1", "规格1", QuotationTypeEnum.ACCESSORY.getValue()));
        items.add(new QuotationItemsVO("配件2", "规格2", QuotationTypeEnum.ACCESSORY.getValue()));
        items.add(new QuotationItemsVO("主材合计", "元", QuotationTypeEnum.SUM_MAIN_MATERIALS.getValue()));
        items.add(new QuotationItemsVO("主材单价", "元/米", QuotationTypeEnum.UNIT_MAIN_MATERIALS.getValue()));
        items.add(new QuotationItemsVO("制作费", "元/米", QuotationTypeEnum.PRODUCE_COST.getValue()));
        items.add(new QuotationItemsVO("喷涂", "元/米", QuotationTypeEnum.SPRAY.getValue()));
        items.add(new QuotationItemsVO("辅材", "元/米", QuotationTypeEnum.AUXILIARY_MATERIALS.getValue()));
        items.add(new QuotationItemsVO("运输", "元/米", QuotationTypeEnum.TRANSPORT.getValue()));
        items.add(new QuotationItemsVO("安装", "元/米", QuotationTypeEnum.INSTALL.getValue()));
        items.add(new QuotationItemsVO("利润", "元/米", QuotationTypeEnum.PROFIT.getValue()));
        items.add(new QuotationItemsVO("出厂单价", "元/米", QuotationTypeEnum.FACTORY_UNIT_PRICE.getValue()));
        items.add(new QuotationItemsVO("税金", "元/米", QuotationTypeEnum.TAXES.getValue()));
        items.add(new QuotationItemsVO("综合单价", "元/米", QuotationTypeEnum.COMPREHENSIVE_UNIT_PRICE.getValue()));
        detail.setList(items);
        return detail;
    }

    /**
     * 添加/更新报价单
     * @param form
     * @return
     */
    public ResponseDTO<String> addOrUpdate(@Valid QuotationUpdateForm form) {
        List<QuotationItemsVO> nullSumList = form.getList().stream().filter(item -> item.getSumOfMoney() == null).toList();
        if (!nullSumList.isEmpty()) {
            return ResponseDTO.error(UserErrorCode.QUOTATION_SUM_OF_MONEY_EMPTY, "报价金额不能为空");
        }
        for (int i = 0; i < form.getList().size(); i++) {
            form.getList().get(i).setSerialNumber(i+1);
        }
        if (form.getQuotationId() == null || form.getQuotationId() == -1) {
            // 全部新增
            addQuotationInfo(SmartBeanUtil.copy(form, QuotationEntity.class),
                    SmartBeanUtil.copyList(form.getList(), QuotationItemsEntity.class));
        } else {
            updateQuotationInfo(SmartBeanUtil.copy(form, QuotationEntity.class),
                    SmartBeanUtil.copyList(form.getList(), QuotationItemsEntity.class));
        }
        return ResponseDTO.ok();
    }

    private void addQuotationInfo(QuotationEntity entity, List<QuotationItemsEntity> items) {
        Long userId = SmartRequestUtil.getRequestUserId();
        entity.setCreateUserId(userId);
        entity.setDisabledFlag(0);
        quotationDao.insert(entity);
        dataTracerService.insert(entity.getQuotationId(), DataTracerTypeEnum.QUOTATION);
        for (int i = 0; i < items.size(); i++) {
            QuotationItemsEntity item = items.get(i);
            item.setQuotationId(entity.getQuotationId());
            item.setCreateUserId(userId);
            quotationItemsDao.insert(item);
            dataTracerService.insert(item.getQuotationItemId(), DataTracerTypeEnum.QUOTATION_ITEM);
        }
    }

    private void updateQuotationInfo(QuotationEntity entity, List<QuotationItemsEntity> items) {
        Long userId = SmartRequestUtil.getRequestUserId();
        entity.setUpdateUserId(userId);
        QuotationEntity oldEntity = quotationDao.selectById(entity.getQuotationId());
        entity.setProjectId(oldEntity.getProjectId());
        quotationDao.updateById(entity);
        dataTracerService.update(entity.getQuotationId(), DataTracerTypeEnum.QUOTATION, oldEntity, entity);

        List<QuotationItemsVO> oldEntities = quotationDao.queryItemsById(entity.getQuotationId());
        List<QuotationItemsEntity> newEntities = items.stream().filter(item -> item.getQuotationItemId() == null).toList();
        List<QuotationItemsEntity> updateEntities = items.stream().filter(item -> item.getQuotationItemId() != null).toList();
        if (!newEntities.isEmpty()) {
            newEntities.forEach(item -> {
                item.setCreateUserId(userId);
                quotationItemsDao.insert(item);
                dataTracerService.insert(item.getQuotationItemId(), DataTracerTypeEnum.QUOTATION_ITEM);
            });
        }

        if (!oldEntities.isEmpty()) {
            Map<Long, QuotationItemsEntity> map = updateEntities.stream().collect(Collectors.toMap(QuotationItemsEntity::getQuotationItemId, item -> item));
            oldEntities.forEach(old -> {
                QuotationItemsEntity update = map.get(old.getQuotationItemId());
                if (update == null) { // 删除
                    update = SmartBeanUtil.copy(old, QuotationItemsEntity.class);
                    update.setDeletedFlag(1);
                }
                update.setUpdateUserId(userId);
                quotationItemsDao.updateById(update);
                dataTracerService.update(update.getQuotationItemId(), DataTracerTypeEnum.QUOTATION_ITEM,
                        SmartBeanUtil.copy(old, QuotationTemplateItemsEntity.class), update);
            });
        }
    }

    public PageResult<QuotationItemsVO> queryItemsPage(@Valid QuotationItemsQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<QuotationItemsVO> list = quotationDao.queryItemsPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    public QuotationDetailVo querySortDetail(Long quotationId) {
        QuotationEntity entity = quotationDao.selectById(quotationId);
        return SmartBeanUtil.copy(entity, QuotationDetailVo.class);
    }
}
